package com.studentstreet.tools.dbhelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.google.gson.Gson;
import com.studentstreet.entities.UserEntity;

public class UserDBHelper {
	private DBHelper dbHelper = null;

	public UserDBHelper(Context context) {
		super();
		dbHelper = new DBHelper(context);
	}

	// 将数据保存到数据库
	public long saveToDB(String json) {
		Gson gson = new Gson();
		UserEntity user = gson.fromJson(json, UserEntity.class);
		return saveToDB(user);
	}

	// 将数据保存到数据库
	public long saveToDB(UserEntity user) {
		long row = 0;
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		// 将旧数据删除
		db.delete(DBTools.TABLE_USER, DBTools.USER_ID + " = " + user.getId(),
				null);

		ContentValues values = new ContentValues();
		values.put(DBTools.USER_ID, user.getId());
		values.put(DBTools.USER_ADDR, user.getAddr());
		values.put(DBTools.USER_SEX, user.getSex());
		values.put(DBTools.USER_HEAD, user.getHeadImgUrl());
		values.put(DBTools.USER_EMAIL, user.getEmail());
		values.put(DBTools.USER_NAME, user.getName());
		values.put(DBTools.USER_PASSWORD, user.getPassword());
		values.put(DBTools.USER_TEL, user.getTel());
		values.put(DBTools.USER_CAMPUS, user.getCampus());
		values.put(DBTools.USER_ORIGIN, user.getOrigin());
		values.put(DBTools.USER_REGTIME, user.getRegTime());

		row = db.insert(DBTools.TABLE_USER, null, values);
		db.close();
		return row;
	}

	// 查询是否有特定用户数据
	public UserEntity getUser(String userName) {
		UserEntity user = new UserEntity();
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(DBTools.TABLE_USER, null, DBTools.USER_NAME
				+ " like '" + userName + "'", null, null, null, null);
		if (cursor.getCount() != 0) {
			cursor.moveToNext();
			user.setId(cursor.getInt(0));
			user.setName(cursor.getString(1));
			user.setHeadImgUrl(cursor.getString(2));
			user.setEmail(cursor.getString(3));
			user.setPassword(cursor.getString(4));
			user.setSex(cursor.getString(5));
			user.setTel(cursor.getString(6));
			user.setAddr(cursor.getString(7));
			user.setOrigin(cursor.getString(8));
			user.setCampus(cursor.getString(9));
			user.setRegTime(cursor.getString(10));
		}
		cursor.close();
		db.close();
		return user;
	}
}
